#pragma once
#include<iostream>
using namespace std;
#include<unistd.h>

typedef void (*work_t)(int);    //函数指针类型，用来接收worker函数，进行回调
typedef void (*task_t)(int, pid_t);

void PrintLog(int fd, pid_t pid)
{
    cout << "sub process: " << pid << ", fd: " << fd<< ", task is : printf log task\n" << endl;
}

void ReLoadConf(int fd, pid_t pid)
{
    cout << "sub process: " << pid << ", fd: " << fd<< ", task is :reload conf task\n" << endl;
}

void ConnectMysql(int fd, pid_t pid)
{
    cout << "sub process: " << pid << ", fd: " << fd<< ", task is : connect mysql task\n" << endl;
}

task_t task[3] = {PrintLog, ReLoadConf, ConnectMysql};  //函数指针类型数组，将各个任务函数名存下来

uint32_t NextTask()
{
    return rand() % 3;  // 0 1 2  随机取一个
}

void worker(int fd)
{
    while (true)
    {
        uint32_t command_code = 0;
        ssize_t n = read(0, &command_code, sizeof(command_code));   //子进程阻塞等待，不断读0所指向，因为重定向
        //所以就算从管道文件里面不停读，直到读到正确的任务码
        if(n == sizeof(command_code))
        {
            if(command_code>=3) continue;
            task[command_code](fd, getpid());
        }
        else if(n == 0)
        {
            cout<<"sub process: "<<getpid()<<"quit now..."<<endl;
            break;
        }
    }
}